package com.lej.dataservice.club.http.interceptor

import com.lej.core.base.BaseApplication
import com.lej.core.daq.DAQEvent
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.IOException
import java.util.concurrent.TimeUnit

/**发送数据*/
class EventInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        if (BaseApplication.instance.isDebug) {
            return chain.proceed(request)
        }

        val st = System.nanoTime()
        val response = chain.proceed(request)
        val segment = slashSegments(request.url.encodedPathSegments)
        val chainMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - st)
        val code = response.code
        val isSuccessful = response.isSuccessful
        val responseBody = response.body
        val contentType = responseBody?.contentType()
        val subtype = contentType?.subtype
        val body = if (subtype != null && (subtype.contains("json")
                    || subtype.contains("xml")
                    || subtype.contains("plain")
                    || subtype.contains("html"))
        ) {
            val bodyString = responseBody.string()
            DAQEvent.http_error.eventHttp(chainMs, isSuccessful, code, bodyString, segment)
            bodyString.toResponseBody(contentType)
        } else {
            return response
        }
        return response.newBuilder().body(body).build()
    }

    private fun slashSegments(segments: List<String>): String {
        val segmentString = StringBuilder("")
        for (segment in segments) {
            segmentString.append("/").append(segment)
        }
        return segmentString.toString()
    }
}